package com.jcl.kaptch.web;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class KaptchaController {

    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/img")
    public void getKaptcha(HttpServletResponse response) throws IOException {
        String text = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(text);
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    @GetMapping("/getCode")
    public String getCode(HttpSession session) {
        return ((String) session.getAttribute("kaptchaCode"));
    }
}
